package br.com.guardaroupavirtual.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.guardaroupavirtual.facade.Facade;
import br.com.guardaroupavirtual.helper.DataHelper;
import br.com.guardaroupavirtual.helper.Diretorios;
import br.com.guardaroupavirtual.helper.HibernateHelper;
import br.com.guardaroupavirtual.helper.LoginFacebook;
import br.com.guardaroupavirtual.model.Usuario;

@WebServlet(value="/UsuarioController", name="UsuarioController")
public class UsuarioController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private HttpServletRequest request;
	private HttpServletResponse response;
	
	private Facade fachada;
	
	private Session session;
	private Transaction transaction;
	
	private String cmd;	
	
	private LoginFacebook loginFacebook;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		this.request = request;
		this.response = response;
		
		cmd = request.getParameter("cmd");
		
		if (cmd == null || cmd.isEmpty()) {		
			request.getRequestDispatcher("Home").forward(request, response);
		}else{			
			if(cmd.equalsIgnoreCase("cadastrar")){
				request.getRequestDispatcher(String.format(Diretorios.Usuario, "cadastra_usuario.jsp")).forward(request, response);
			}
			if (cmd.equalsIgnoreCase("alterar")) {
				session = HibernateHelper.getSessionFactory().openSession();
				fachada = Facade.getCurrentInstance();
				Usuario usuario = fachada.getUsuario(session, Integer.parseInt(request.getParameter("id")));
				Usuario usuarioSessao = (Usuario) request.getSession().getAttribute("usuario");
				if(usuario.getId() != usuarioSessao.getId()){
					request.setAttribute("usuarios", this.getUsuarios());
					request.setAttribute("mensagem", "Usuário não encontrado!");
					request.getRequestDispatcher(String.format(Diretorios.Usuario, "lista_usuario.jsp")).forward(request, response);					
				}
				request.setAttribute("usuario", usuario);
				request.getRequestDispatcher(String.format(Diretorios.Usuario, "altera_usuario.jsp")).forward(request, response);				
			}
			
			if(cmd.equalsIgnoreCase("logar")){
				request.getRequestDispatcher(String.format(Diretorios.Usuario, "login.jsp")).forward(request, response);
			}
			
			if(cmd.equalsIgnoreCase("logarFacebook")){
				this.logarFacebook();
			}				
			
			if(cmd.equalsIgnoreCase("deslogar")){
				request.getSession().setAttribute("usuario", null);
				request.getRequestDispatcher(String.format(Diretorios.Usuario, "login.jsp")).forward(request, response);
			}				
		}	
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.request = request;
		this.response = response;
		
		cmd = request.getParameter("cmd");
		
		if (cmd.equalsIgnoreCase("cadastrar")) {
			this.cadastrar();
		}
		if (cmd.equalsIgnoreCase("alterar")) {
			this.alterar();
		}
		
		if(cmd.equalsIgnoreCase("logar") ){
			this.logar();
		}		
		
	}
	
	private List<Usuario> getUsuarios(){
		fachada = Facade.getCurrentInstance();
		session = HibernateHelper.getSessionFactory().openSession();
		return fachada.getUsuarios(session);
	}
	
	private void cadastrar() throws ServletException, IOException{
		try {
			
			//Abrindo a conexão com o banco de dados
			session = HibernateHelper.getSessionFactory().openSession();
			//Iniciando uma transação
			transaction = session.beginTransaction();
			
			Usuario usuario = new Usuario();
			usuario.setEmail(request.getParameter("email"));
			usuario.setSexo(request.getParameter("sexo"));
			usuario.setMedida(request.getParameter("medida"));
			usuario.setSenha(request.getParameter("senha"));
			usuario.setDataNascimento(DataHelper.stringToDate(request.getParameter("dataNascimento")));			
			
			fachada = Facade.getCurrentInstance();
			fachada.cadastrarUsuario(session, usuario);
			
			transaction.commit();
			request.setAttribute("mensagem", "Registro inserido com sucesso!");
		} catch (Exception e) {
			transaction.rollback();
			request.setAttribute("mensagem", "Ocorreu um erro ao tentar inserir o registro!");
		}
		request.setAttribute("usuarios", this.getUsuarios());
		request.getRequestDispatcher(String.format(Diretorios.Usuario, "login.jsp")).forward(request, response);
	}
	
	private void alterar() throws ServletException, IOException{
		Usuario usuario = null;
		try {			
			session = HibernateHelper.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			
			fachada = Facade.getCurrentInstance();
			usuario = fachada.getUsuario(session, Integer.parseInt(request.getParameter("id")));
			usuario.setEmail(request.getParameter("email"));
			usuario.setSexo(request.getParameter("sexo"));
			usuario.setMedida(request.getParameter("medida"));
			usuario.setSenha(request.getParameter("senha"));
			usuario.setDataNascimento(DataHelper.stringToDate(request.getParameter("dataNascimento")));			

			fachada.alterarUsuario(session, usuario);
			transaction.commit();
			request.setAttribute("mensagem", "Registro alterado com sucesso!");
		} catch (Exception e) {
			transaction.rollback();
			request.setAttribute("mensagem", "Ocorreu um erro ao tentar alterar o registro!");
		}
		request.setAttribute("usuario", usuario);
		request.getRequestDispatcher(String.format(Diretorios.Usuario, "altera_usuario.jsp")).forward(request, response);		
	}
	

	
	private void deletar() throws ServletException, IOException{
		session = HibernateHelper.getSessionFactory().openSession();
		transaction = session.beginTransaction();
		fachada = Facade.getCurrentInstance();
		
		try {
			int id = Integer.parseInt(request.getParameter("id"));
			Usuario usuario = fachada.getUsuario(session, id);
			fachada.deletarUsuario(session, usuario);
			transaction.commit();
			request.setAttribute("mensagem", "Registro excluido com sucesso!");			
		} catch (Exception e) {
			transaction.rollback();
			request.setAttribute("mensagem", "Ocorreu um erro ao tentar excluir o registro!");
		}
		request.setAttribute("usuarios", this.getUsuarios());
		request.getRequestDispatcher(String.format(Diretorios.Usuario, "lista_usuario.jsp")).forward(request, response);			
	}
	
	private void logar() throws ServletException, IOException{
		fachada = Facade.getCurrentInstance();
		session = HibernateHelper.getSessionFactory().openSession();			
		
		Usuario usuario = fachada.logar(session, request.getParameter("email").toString(), request.getParameter("senha").toString());
		
		if (usuario != null) {
			request.getSession().setAttribute("usuario", usuario);
			request.getRequestDispatcher(String.format(Diretorios.Home, "index.jsp")).forward(request, response);				
		}else{
			request.setAttribute("mensagem", "Usuário ou senha inválido!");
			request.getRequestDispatcher(String.format(Diretorios.Usuario, "login.jsp")).forward(request, response);
		}		
	}
	
	private void logarFacebook() throws ServletException, IOException{
		loginFacebook = new LoginFacebook();
		this.response.sendRedirect(loginFacebook.getLoginRedirectURL());
	}
	
	
}
